<?php

namespace Module\Admin;

use W3\Filer;
use Theme\Config;
use Manager\Options as Manager;
use W3\Html;
use W3\Exception;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 编辑风格组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Theme extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'admin.theme',
			
		], true);
		
		# 必须为管理员以上权限
		$this->auth->check('admin');
	}
	
    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->on(!$this->request->action || $this->request->is('action=index'))->index();
		$this->on($this->request->is('action=edit'))->editFile();
		$this->on($this->request->isPost() && $this->request->is('action=edit'))->editFileSave();
		$this->on($this->request->is('action=config'))->_config();
		$this->on($this->request->isPost() && $this->request->is('action=config'))->configSave();
		$this->on($this->request->is('action=change'))->changeTheme();
    }	
	
    public function index()
    {
		/** 输出内容 */
		$this->layout->set($this->themesList(), 'body');

		$this->view();
    }
	
    public function themesList()
    {
		$html = '';
		
		$this->widget('Theme\Rows')->to($themes);
		
		if ($themes->have()) {
			$table = Html::table();
			
			$table->thead->preppend('
                <colgroup>
                    <col width="35%" />
                    <col />
                </colgroup>
			');
			
			$table->head([
			    __('截图'),
				__('详情'),
			]);
		
			while ($themes->next()){
				
                $parseStr = 
				'<h3>'.('' != $themes->title ? $themes->title : $themes->name).'</h3>
                <div class="cite">';
                if($themes->author){
					$parseStr .= __('作者').': ';
					if($themes->homepage){
						$parseStr .= '<a href="'.$themes->homepage.'">' . $themes->author . '</a>';
					} else {
					    $parseStr .= $themes->author;
					}					
					$parseStr .= '&nbsp;&nbsp;';
				}
                if($themes->version){
					$parseStr .= __('版本').': '.$themes->version;
				}
                $parseStr .= '</div>
                <p>'.nl2br($themes->description).'</p>';
                $parseStr .= '<p>' . Html::a($this->adminUrl('theme/edit', 'theme=' . $themes->name, false), __('编辑'))->addClass('btn btn-primary px-2 py-1 mb-2');
                if($this->config->theme != $themes->name){
                    $parseStr .= Html::a($this->adminUrl('theme/change', 'change=' . $themes->name, false), __('启用'))->addClass('btn btn-primary px-2 py-1 mb-2');
				}
                if ($this->config->theme == $themes->name && $this->widget('Theme\Config')->isExists()){
                    $parseStr .= Html::a($this->adminUrl('theme/config', false), __('设置'))->addClass('btn btn-primary px-2 py-1 mb-2');
                }
				$parseStr .= '</p>';

			    $table->body([
				    '<img src="'.$themes->screen.'" alt="'.$themes->name.'" />',
				    $parseStr
				]);
			}
		
		    $html .= $table->render();
        }
		return $html;
	}
	
    public function editFile()
    {
		$this->parameter->title = __('编辑文件: %s', [$this->request->filter('strip_tags')->theme . ' : ' . $this->request->filter('strip_tags')->get('file', 'index.php')]);
		
		/** 输出内容 */
		$this->layout->set($this->themesEditor(), 'body');

		$this->view();
    }
	
    /**
     * 编辑外观文件
     *
     * @access public
     * @param string $theme 外观名称
     * @param string $file 文件名
     * @return void
     */
    public function editFileSave()
    {
        $theme = $this->request->filter('strip_tags')->theme;
        $file = $this->request->filter('strip_tags')->get('file', 'index.php');
		$content = $this->request->content;
        $path = $this->themeFile($file, $theme);

        if (Filer::exists($path) && Filer::isWritable($path)) {
            if (Filer::put($path, $content, 'wb')) {
                $this->notice(__("文件 %s 的更改已经保存", [$file]));
            } else {
                $this->notice(__("文件 %s 无法被写入", [$file]), 'notice');
            }
			
			$this->goBack();
			
        } else {
			throw new Exception(__('您编辑的文件不存在'));
        }
    }
	
    public function themesEditor()
    {
		$this->widget('Theme\Files')->to($files);
		$html = '';
		if ($files->have()) {
			$table = Html::table();
			
			$table->thead->preppend('
                <colgroup>
                    <col />
					<col width="30%" />
                </colgroup>
			');
			
		    $right = '<h3>'.__('模板文件').'</h3>';
            while($files->next())
			{
				$button = Html::a($this->adminUrl('theme/edit', false) . '?theme=' . $files->currentTheme() . '&file=' . $files->file, $files->file)->addClass('btn btn-sm mb-2');
				$files->current && $button->addClass('btn-primary');
				
                $right .= $button;
            }

		    /** 构建表格 */
            $form = Html::form()->style('max-width: 100%;height: 100%;');

            $content = Html::textarea('content', $files->currentContent());
		    !$files->currentIsWriteable() && $content->disabled();
            $form->addInput($content);
			$content->style('padding:10px;height: 600px;width: 100%;overflow: auto;');
		
		    $theme = Html::hidden('theme', $files->currentTheme());
            $form->addInput($theme);
			
		    $edit = Html::hidden('edit', $files->currentFile());
            $form->addInput($edit);
		
            /** 提交按钮 */
            $submit = Html::submit(__('保存文件'));
		    !$files->currentIsWriteable() && $submit->disabled();
            $form->set($submit);

		    $table->body([
			    $form->render(),
			    $right
		    ]);
		    $html .= $table->render();
		}
		return $html;
	}
	
	
    /**
     * 更换外观
     *
     * @access public
     * @param string $theme 外观名称
     * @return void
     */
    public function changeTheme()
    {
		$theme = $this->request->filter('strip_tags')->change;
        $theme = trim($theme, './');
        if (is_dir($this->themeFile('', $theme))) {
			
            /** 删除原外观设置信息 */
            $this->deleteOptions('theme:' . $this->config->theme);

            $this->updateOptions('theme', $theme);

			$this->notice(__("外观已经改变"));
			
			$this->goBack();
			
        } else {
			
			throw new Exception(__('您选择的风格不存在'), 404);
        }
    }

    /**
     * 配置外观
     *
     * @access public
     * @param string $theme 外观名
     * @return void
     */
    public function _config()
    {
		$theme = $this->config->theme;
		
        // 已经载入了外观函数
        $form = $this->widget('Theme\Config')->form();
		
		/** 输出内容 */
		$this->layout->set($form, 'body');

		$this->view();
    }
    
    /**
     * 配置外观
     *
     * @access public
     * @param string $theme 外观名
     * @return void
     */
    public function configSave()
    {
		$theme = $this->config->theme;
		
        // 已经载入了外观函数
        $form = $this->widget('Theme\Config')->form();
		
		/** 验证表单 */
        if ($form->validate()) {
            $this->goBack();
        }

        $settings = $form->getAllRequest();

        if (isset($this->config->{'theme:' . $theme})) {
            $this->updateOptions('theme:' . $theme, $settings);
        } else {
            $this->addOptions('theme:' . $theme, $settings);
        }

        /** 提示信息 */
        $this->notice(__("外观设置已经保存"));
		
		$this->goBack();
    }

}
